/**
 * 
 */
package com.smarthome.core.workingmonitor.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.smarthome.base.service.ShSmsRecordService;
import com.smarthome.core.workingmonitor.MessageWorkService;
import com.smarthome.domain.bean.ShSmsRecord;
import com.smarthome.rpc.sms.SmsClient;

/**
 * @author dhc
 * @date 2016年4月27日 下午9:52:17
 * @title
 */
@Service("messageWorkService")
public class MessageWorkServiceImpl implements MessageWorkService {

    private static Logger logger = Logger.getLogger(MessageWorkServiceImpl.class);
    @Resource(name = "shSmsRecordService")
    private ShSmsRecordService recordService;

    /*
     * (non-Javadoc)
     * @see com.smarthome.core.workingmonitor.MessageWorkService#doStatus()
     */
    @Override
    // @Scheduled(cron="0 0/10 * * * ?")//配置了独立的任务管理
    public void doStatus() {
        String statusStr = SmsClient.getStatus();
        if (StringUtils.isBlank(statusStr))
            return;

        logger.info(String.format("获取短信回执信息：",statusStr));
        String[] arr = statusStr.split("\n");
        if (arr.length <= 1)
            return;

        for (int i = 1; i <arr.length; i++) {
            // 1461751302378#15202834325#0
            String[] arr2 = arr[i].split("#");

            ShSmsRecord record = new ShSmsRecord();
            record.setUrid(arr2[0]);
            record.setMobile(arr2[1]);
            List<ShSmsRecord> records = recordService.selectEntryList(record);
            if (records.isEmpty()) {
                record.setErrorDate(new Date());
                record.setErrorMsg(String.format("发送源头未知短息,错误码 %s" ,arr2[2]));
                record.setStatus(2);
                record.setTemplet(false);
                record.setTypeId(0l);
                record.setTypeName("未使用模板");
                recordService.insert(record);
            } else {
                ShSmsRecord queryrRecord = records.get(0);
                if ("0".equals(arr2[2])) {
                    // 成功
                    queryrRecord.setStatus(1);
                } else {
                    queryrRecord.setStatus(2);
                }
                recordService.saveOrUpdate(queryrRecord);
            }
        }
    }
}
